package com.example.superyi.mainBar.fregments;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.room.entity.MyJoinTeam;
import com.example.room.entity.PublicTeam;
import com.example.superyi.myteam.R;
import com.example.superyi.myteam.abilitybox.createteams.CreateTeamActivity;
import com.example.superyi.myteam.databinding.MainFragmentDBinding;
import com.example.wjy.MyTeamActivity;
import com.example.wjy.adapter.PublicTeamAdapter;
import com.example.wjy.viewmodels.PublicTeamViewModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Mianfragment_Team extends Fragment implements View.OnClickListener {

//    Button button,button1;
    MainFragmentDBinding binding;

    Toolbar toolbar;
    PublicTeamViewModel publicTeamViewModel;
    PublicTeamAdapter publicTeamAdapter;
    RecyclerView recyclerView;
    public SwipeRefreshLayout swipeRefreshLayout;
    public String url = "http://49.232.60.155:8080/AppServer_war/TeamServlet";

    public List<PublicTeam> teams;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment_d,container,false);
        Log.v("test","----------------运行到此处fragmentA_homepage");
//        binding = MainFragmentDBinding.inflate(inflater,container,false);
//        button = view.findViewById(R.id.button);
//        button1 = view.findViewById(R.id.my_team);
        recyclerView = view.findViewById(R.id.public_team);
        swipeRefreshLayout = view.findViewById(R.id.swipe);
        toolbar = view.findViewById(R.id.toolbar4);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.v("test","----------------运行到此处fragment的onViewcreated");

        publicTeamViewModel = new ViewModelProvider(requireActivity()).get(PublicTeamViewModel.class);

        publicTeamAdapter = new PublicTeamAdapter(publicTeamViewModel.getAllTeams().getValue());
        publicTeamAdapter.setContext(requireActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(publicTeamAdapter);

        publicTeamViewModel.getAllTeams().observe(requireActivity(), new Observer<List<PublicTeam>>() {
            @Override
            public void onChanged(List<PublicTeam> teams) {
                publicTeamAdapter.setTeamList(teams);
                publicTeamAdapter.notifyDataSetChanged();
            }
        });



        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();
            //传递的参数是以键值对传输的

            RequestBody requestBody = new FormBody.Builder()
                    .add("flag","6")
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            Call call =  client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String json = response.body().string();
                    Gson gson = new Gson();
                    teams = gson.fromJson(json,new TypeToken<List<PublicTeam>>(){}.getType());
                    publicTeamViewModel.deleteTeam();
                    if(teams != null)
                        for(int i = 0;i < teams.size();++i)
                            publicTeamViewModel.insertTeam(teams.get(i));
                }
            });

        }).start();



    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            new Thread(() -> {
                OkHttpClient client = new OkHttpClient();
                //传递的参数是以键值对传输的

                RequestBody requestBody = new FormBody.Builder()
                        .add("flag","6")
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                Call call =  client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String json = response.body().string();
                        Gson gson = new Gson();
                        teams = gson.fromJson(json,new TypeToken<List<PublicTeam>>(){}.getType());
                        publicTeamViewModel.deleteTeam();
                        if(teams != null)
                            for(int i = 0;i < teams.size();++i)
                                publicTeamViewModel.insertTeam(teams.get(i));
                    }
                });

            }).start();
//            Toast.makeText(requireActivity(), "这是发布组队的页面", Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.button:
//                Intent intent  = new Intent(getActivity(), CreateTeamActivity.class);
//                startActivity(intent);
//                break;
            default:break;
        }
    }
}